package com.xjiye_test.payServer.servletGroup.shemmapay;

import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.db.Entity;
import com.xiaoleilu.hutool.db.Page;
import com.xiaoleilu.hutool.db.PageResult;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.log.StaticLog;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xjiye_test.payServer.bean.CheckOrder;
import com.xjiye_test.payServer.bean.QueryPage;
import com.xjiye_test.payServer.dao.SmfOrderDao;
import com.xjiye_test.payServer.serverletInit.Config;
import com.xjiye_test.payServer.serverletUtil.*;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.collections.ArrayStack;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/6/1.
 */
public class CheckOrderBusiness extends HttpServlet {

    int testPayShort; //支付短款订单数控制
    int testPayLong; //支付长款订单数控制
    int testRefundShort; //退款短款订单数控制
    int testRefundLong; //退款长款订单数控制
    int testAmount;//金额出错订单数控制


    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        testPayShort=0;
        testPayLong=0;
        testRefundShort=0;
        testRefundLong=0;
        testAmount=0;
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        String reStr=null;
        JSONObject json=new JSONObject();
        json.put("msg",new JSONObject());
        try {
            int targetPage=Integer.parseInt(req.getParameter("targetPage"));
            int pageSize=Integer.parseInt(req.getParameter("pageSize"));
//            int size = req.getContentLength();
//            InputStream is = req.getInputStream();
//            Map mapRequest =  XMLParser.getMapFromXML(new String(ReadBytes.readBytes(is, size)));
            SmfOrderDao smf=new SmfOrderDao();
            List<String> keys= new ArrayList<>();
            List<String> values= new ArrayList<>();
            //Map<String,String> orderMap=new HashMap<>();
            keys.add("sid=");
            values.add(req.getParameter("accountId"));
            keys.add("time<=");
            values.add(DateUtil.parse(req.getParameter("billDate")+" 23:59:59", "yyyyMMdd HH:mm:ss")+"");
            keys.add("time>=");
            values.add(DateUtil.parse(req.getParameter("billDate")+" 00:00:00", "yyyyMMdd HH:mm:ss")+"");
            PageResult<Entity> orders=smf.getDataByCondition(new Page(targetPage,pageSize),keys,values);
            int[] orderTest=TestParser.getOrderTest(GlobalVariable.test);
            QueryPage page=new QueryPage();
            page.setPageSize(pageSize);
            page.setTargetPage(targetPage);
            page.setRecordCount(orders.size());
            page.setTotalCount(orders.getTotal());
            if(orderTest[0]==0){
                page.setRecordCount(page.getRecordCount()-2);
                page.setTotalCount(page.getTotalCount()-2);
            }
            if(orderTest[0]==2){
                page.setRecordCount(page.getRecordCount()+2);
                page.setTotalCount(page.getTotalCount()+2);
            }
            if(orderTest[1]==0){
                page.setRecordCount(page.getRecordCount()-2);
                page.setTotalCount(page.getTotalCount()-2);
            }
            if(orderTest[1]==2){
                page.setRecordCount(page.getRecordCount()+2);
                page.setTotalCount(page.getTotalCount()+2);
            }
            json.getJSONObject("msg").put("queryPage", JSONUtil.toJsonStr(page));
            List<CheckOrder> resultLists=new ArrayList<>();
            for(int i=0;i<orders.size();i++){
                if(0==orders.get(i).getInt("status")){
                    if(orderTest[0]==0){
                        if(testPayShort<2){
                            testPayShort++;
                            StaticLog.error("测试业务少支付订单:订单号 "+orders.get(i).getStr("order_no"));
                            continue;
                        }else{
                            resultLists.add(getCheckOrder(orders.get(i),orderTest));
                        }
                    }else {
                        resultLists.add(getCheckOrder(orders.get(i),orderTest));
                    }
                }else{
                    if(orderTest[1]==0){
                        if(testRefundShort<2){
                            testRefundShort++;
                            StaticLog.error("测试业务少退款订单:订单号 "+orders.get(i).getStr("order_no"));
                            continue;
                        }else{
                            resultLists.add(getCheckOrder(orders.get(i),orderTest));
                        }
                    }else {
                        resultLists.add(getCheckOrder(orders.get(i),orderTest));
                    }
                }
            }
            if(orderTest[0]==2){
                //第一个订单
                CheckOrder check1=new CheckOrder();
                int newAmount1=NumberUtil.generateRandomNumber(1,999999,1)[0];
                check1.setAmount(newAmount1);
                check1.setFee((int)NumberUtil.round(NumberUtil.mul(newAmount1,0.003),0));
                String orderNo1=IdWorker.getIdWorker().nextId()+"";
                check1.setOrderNo(orderNo1);
                check1.setRefundAmount(0);
                check1.setAccountId(req.getParameter("accountId"));
                check1.setTxDate(DateUtil.parse(req.getParameter("billDate")+" 13:23:23", "yyyy-MM-dd HH:mm:ss")+"");
                check1.setTxType("PAYMENT");
                //第二个订单
                CheckOrder check2=new CheckOrder();
                int newAmount2=NumberUtil.generateRandomNumber(1,999999,1)[0];
                check2.setAmount(newAmount2);
                check2.setFee((int)NumberUtil.round(NumberUtil.mul(newAmount2,0.003),0));
                String orderNo2=IdWorker.getIdWorker().nextId()+"";
                check2.setOrderNo(orderNo2);
                check2.setRefundAmount(0);
                check2.setAccountId(req.getParameter("accountId"));
                check2.setTxDate(DateUtil.parse(req.getParameter("billDate")+" 13:23:23", "yyyy-MM-dd HH:mm:ss")+"");
                check2.setTxType("PAYMENT");
                resultLists.add(check1);
                StaticLog.error("测试业务多支付订单:订单号 "+orderNo1);
                resultLists.add(check2);
                StaticLog.error("测试业务多支付订单:订单号 "+orderNo2);
            }
            if(orderTest[1]==2){
                //第一个订单
                CheckOrder check3=new CheckOrder();
                check3.setAmount(0);
                check3.setFee(0);
                String orderno3=IdWorker.getIdWorker().nextId()+"";
                check3.setOrderNo(orderno3);
                check3.setRefundAmount(NumberUtil.generateRandomNumber(1,999999,1)[0]);
                check3.setAccountId(req.getParameter("accountId"));
                check3.setTxDate(DateUtil.parse(req.getParameter("billDate")+" 13:23:23", "yyyyMMdd HH:mm:ss")+"");
                check3.setTxType("REFUND");
                //第二个订单
                CheckOrder check4=new CheckOrder();
                check4.setAmount(0);
                check4.setFee(0);
                String orderno4=IdWorker.getIdWorker().nextId()+"";
                check4.setOrderNo(orderno4);
                check4.setRefundAmount(NumberUtil.generateRandomNumber(1,999999,1)[0]);
                check4.setAccountId(req.getParameter("accountId"));
                check4.setTxDate(DateUtil.parse(req.getParameter("billDate")+" 13:23:23", "yyyyMMdd HH:mm:ss")+"");
                check4.setTxType("REFUND");
                resultLists.add(check3);
                StaticLog.error("测试业务多退款订单:订单号 "+orderno3);
                resultLists.add(check4);
                StaticLog.error("测试业务多退款订单:订单号 "+orderno4);
            }
            json.getJSONObject("msg").put("resultList",JSONUtil.toJsonStr(resultLists));
            json.put("msgcode","100");
        }catch (Exception e){
            e.printStackTrace();
            json.put("msgcode","200");
            json.put("msg","系统错误");
        }
        finally {
            reStr=json.toString();
            out.print(reStr);
            out.flush();
        }


    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    public CheckOrder getCheckOrder(Entity order,int[] orderTest){
        CheckOrder result=new CheckOrder();
        if(0==order.getInt("status")){
            if(orderTest[0]==3){
                if(testAmount<2){
                    testAmount++;
                    int newAmount=NumberUtil.generateRandomNumber(1,999999,1)[0];
                    result.setAmount(newAmount);
                    result.setFee((int)NumberUtil.round(NumberUtil.mul(newAmount,0.003),0));
                    StaticLog.error("测试业务支付订单金额不一致:订单号 "+order.getStr("order_no")+" 少了"+(newAmount-order.getInt("amount")));
                }else{
                    result.setAmount(order.getInt("amount"));
                    result.setFee(order.getInt("fee"));
                }

            }else{
                result.setAmount(order.getInt("amount"));
                result.setFee(order.getInt("fee"));
            }
            result.setOrderNo(order.getStr("order_no"));
            result.setRefundAmount(0);
            result.setAccountId(order.getStr("sid"));
            result.setTxDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getDate("time")));
            result.setTxType("PAYMENT");
        }else{
            if(orderTest[1]==3){
                if(testAmount<2){
                    testAmount++;
                    int newAmount=NumberUtil.generateRandomNumber(1,999999,1)[0];
                    result.setRefundAmount(newAmount);
                    StaticLog.error("测试业务退款订单金额不一致:订单号 "+order.getStr("order_no")+" 少了"+(newAmount-order.getInt("amount")));
                }else{
                    result.setRefundAmount(order.getInt("amount"));
                }
            }else {
                result.setRefundAmount(order.getInt("amount"));
            }
            result.setAmount(0);
            result.setFee(0);
            result.setOrderNo(order.getStr("order_no"));
            result.setAccountId(order.getStr("sid"));
            result.setTxDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getDate("time")));
            result.setTxType("REFUND");
        }
        return result;
    }
}

